import { Inject, Injectable } from '@nestjs/common';
import { Redis } from 'ioredis';
import { UserTelegram } from 'model';
import TelegramBot from 'node-telegram-bot-api';
import { TelegramBotCommandService } from './telegram-bot-command.service';

@Injectable()
export class TelegramBotService {
    constructor(
        @Inject('TelegramBot')
        private bot: TelegramBot,
        private TelegramBotCommand: TelegramBotCommandService,
        @Inject('Redis')
        private redis: Redis
    ) {
        this.bot.on('message', this.onReceiveMessage);
    }

    private async onlyOneRole(role: string, chatId: string, id: string) {
        if ((await this.redis.get(`id-${id}`)) === role) {
            return true;
        } else {
            return false;
        }
    }

    onReceiveMessage = async (msg: TelegramBot.Message) => {
        const chatId: string = msg.chat.id.toString();
        const textMessage: string | undefined = msg.text;
        const userInform: TelegramBot.User = msg.from!;

        /**
         * Проверка на бота (их сразу отсекаем и баним навеки)
         */
        if (userInform.is_bot) {
            await this.bot.sendMessage(chatId, "Sorry, you'r bot");
            await this.bot.banChatMember(chatId, userInform.id);
            return 0;
        }

        /**
         * Триггер на каждое сообщение, помогает всегда (когда надо) держать роль пользователя в памяти
         */
        if (!textMessage.startsWith('/start')) {
            await this.TelegramBotCommand.triggerCheckRole(userInform.id.toString());
        }

        if (textMessage.startsWith('/start')) {
            const referral: string = textMessage.substring('/start'.length).trim();

            await this.TelegramBotCommand.commandStart(
                chatId,
                new UserTelegram({
                    telegramId: userInform.id.toString(),
                    firstName: userInform.first_name,
                    lastName: userInform.last_name,
                    username: userInform.username,
                    referralCode: referral,
                })
            );
        }

        if (textMessage === 'Cancel') {
            await this.TelegramBotCommand.cancelOneOperation(chatId, userInform.id.toString());
        }

        if (textMessage === 'Back') {
            await this.TelegramBotCommand.backToMenu(chatId, userInform.id.toString());
        }

        if (textMessage === 'Add keys') {
            await this.TelegramBotCommand.goToMenuKeys(chatId, userInform.id.toString());
        }

        if (textMessage === 'Reset keys') {
            await this.TelegramBotCommand.cancelKeys(chatId, userInform.id.toString());
        }

        if (textMessage === 'Add Api Key') {
            await this.TelegramBotCommand.addKey(chatId, userInform.id.toString(), 'apiKey', false, textMessage);
        } else {
            if ((await this.redis.get(`action-id-${userInform.id}`)) === 'apiKey') {
                await this.TelegramBotCommand.addKey(chatId, userInform.id.toString(), 'apiKey', true, textMessage);
            }
        }

        if (textMessage === 'Add Secret Key') {
            await this.TelegramBotCommand.addKey(chatId, userInform.id.toString(), 'secretKey', false, textMessage);
        } else {
            if ((await this.redis.get(`action-id-${userInform.id}`)) === 'secretKey') {
                await this.TelegramBotCommand.addKey(chatId, userInform.id.toString(), 'secretKey', true, textMessage);
            }
        }

        if (textMessage === 'Balance') {
            if (
                (await this.onlyOneRole('user', chatId, userInform.id.toString())) ||
                (await this.onlyOneRole('trader', chatId, userInform.id.toString()))
            ) {
                await this.TelegramBotCommand.goToMenuBalance(chatId, userInform.id.toString());
            } else {
                await this.bot.sendMessage(chatId, 'You are not authorized to use this command');
            }
        }

        if (textMessage === 'Check balance') {
            if (
                (await this.onlyOneRole('user', chatId, userInform.id.toString())) ||
                (await this.onlyOneRole('trader', chatId, userInform.id.toString()))
            ) {
                await this.TelegramBotCommand.checkBalance(chatId, userInform.id.toString());
            } else {
                await this.bot.sendMessage(chatId, 'You are not authorized to use this command');
            }
        }

        if (textMessage === 'Refill balance') {
            if (
                (await this.onlyOneRole('user', chatId, userInform.id.toString())) ||
                (await this.onlyOneRole('trader', chatId, userInform.id.toString()))
            ) {
                await this.TelegramBotCommand.refillBalance(chatId, userInform.id.toString());
            } else {
                await this.bot.sendMessage(chatId, 'You are not authorized to use this command');
            }
        } else {
            if ((await this.redis.get(`action-id-${userInform.id}`)) === 'refill') {
                await this.TelegramBotCommand.refillBalance(chatId, userInform.id.toString(), textMessage);
            }
        }

        if (textMessage === 'Check status') {
            if (
                (await this.onlyOneRole('user', chatId, userInform.id.toString())) ||
                (await this.onlyOneRole('trader', chatId, userInform.id.toString()))
            ) {
                // Заглушка (сказано не делать)
                await this.bot.sendMessage(chatId, 'Some status information');
            } else {
                await this.bot.sendMessage(chatId, 'You are not authorized to use this command');
            }
        }

        if (textMessage === 'Stats') {
            if (
                (await this.onlyOneRole('user', chatId, userInform.id.toString())) ||
                (await this.onlyOneRole('trader', chatId, userInform.id.toString()))
            ) {
                //Заглушка (сказано не делать)
                await this.bot.sendMessage(chatId, 'Statistics');
            } else {
                await this.bot.sendMessage(chatId, 'You are not authorized to use this command');
            }
        }

        if (textMessage === 'Become trader') {
            if (await this.onlyOneRole('user', chatId, userInform.id.toString())) {
                // Заглушка (сказано не делать)
                await this.bot.sendMessage(chatId, "Congratulations, you'r a trader");
            } else {
                await this.bot.sendMessage(chatId, 'You are not authorized to use this command');
            }
        }

        /////////////////////// For traders ///////////////////////////////////////

        if (textMessage === 'Signal') {
            if (await this.onlyOneRole('trader', chatId, userInform.id.toString())) {
                await this.TelegramBotCommand.sendMessageToAllSubscribers(chatId, userInform.id.toString());
            } else {
                await this.bot.sendMessage(chatId, 'You are not authorized to use this command');
            }
        } else {
            if ((await this.redis.get(`action-id-${userInform.id}`)) === 'signal') {
                await this.TelegramBotCommand.sendMessageToAllSubscribers(
                    chatId,
                    userInform.id.toString(),
                    textMessage
                );
            }
        }

        if (textMessage === 'Become user') {
            if (await this.onlyOneRole('trader', chatId, userInform.id.toString())) {
                // Заглушка (сказано не делать)
                await this.bot.sendMessage(chatId, "Congratulations, you'r a user");
            } else {
                await this.bot.sendMessage(chatId, 'You are not authorized to use this command');
            }
        }

        if (textMessage === 'Set nickname') {
            if (await this.onlyOneRole('trader', chatId, userInform.id.toString())) {
                await this.TelegramBotCommand.changeNickname(chatId, userInform.id.toString());
            } else {
                await this.bot.sendMessage(chatId, 'You are not authorized to use this command');
            }
        } else {
            if ((await this.redis.get(`action-id-${userInform.id}`)) === 'setNick') {
                await this.TelegramBotCommand.changeNickname(chatId, userInform.id.toString(), textMessage);
            }
        }

        if (textMessage === 'Referral') {
            if (await this.onlyOneRole('trader', chatId, userInform.id.toString())) {
                await this.TelegramBotCommand.goToMenuRefferal(chatId, userInform.id.toString());
            } else {
                await this.bot.sendMessage(chatId, 'You are not authorized to use this command');
            }
        }

        if (textMessage === 'Get referral') {
            if (await this.onlyOneRole('trader', chatId, userInform.id.toString())) {
                await this.TelegramBotCommand.getReferralCodes(chatId, userInform.id.toString());
            } else {
                await this.bot.sendMessage(chatId, 'You are not authorized to use this command');
            }
        }

        if (textMessage === 'Add referral') {
            if (await this.onlyOneRole('trader', chatId, userInform.id.toString())) {
                await this.TelegramBotCommand.addReferralCodes(chatId, userInform.id.toString());
            } else {
                await this.bot.sendMessage(chatId, 'You are not authorized to use this command');
            }
        } else {
            if ((await this.redis.get(`action-id-${userInform.id}`)) === 'refCode') {
                await this.TelegramBotCommand.addReferralCodes(chatId, userInform.id.toString(), textMessage);
            }
        }
    };
}
